package org.ala.tree.lsm.tools.compression;

/**
 * 字符串前缀压缩
 *
 * @author ala
 * @date 2025年5月28日
 */
public class PrefixCompression {
	/**
	 * 	上一个字符串
	 */
	protected char[] prev;
	
	
	/**
	 *  前缀压缩
	 */
	public Result compression(String str) {
		if (prev == null) {
			prev = str.toCharArray();
			return Result.build(str, 0);
		}
		//	找到差异
		int i = 0;
		char[] cs = str.toCharArray();
		while (i < prev.length && i < cs.length) {
			if (prev[i] != cs[i]) {break;}
			i++;
		}
		//	从差异开始构建结果
		prev = cs;
		return Result.build(new String(cs, i, cs.length - i), i);
	}
	/**
	 * 	压缩还原
	 */
	public String revert(Result r) {
		if (prev == null) {
			prev = r.str.toCharArray();
			return r.str;
		}
		
		String res = null;
		if (r.i == 0) {
			res = r.str;
		} else {
			StringBuilder sbuf = new StringBuilder();
			sbuf.append(new String(prev, 0, r.i));
			sbuf.append(r.str);
			res = sbuf.toString();
		}
		
		prev = res.toCharArray();
		return res;
	}
	
	
	public void reset() {prev = null;}
	
	
	/**
	 * 	前缀压缩结果
	 */
	public static class Result {
		/**
		 * 	差异字符串
		 */
		protected String str;
		/**
		 * 	差异下标
		 */
		protected int i;
		
		
		public static Result build(String str, int i) {
			Result r = new Result();
			r.str = str;
			r.i = i;
			return r;
		}
		
		
		public String getStr() {
			return str;
		}
		public void setStr(String str) {
			this.str = str;
		}
		public int getI() {
			return i;
		}
		public void setI(int i) {
			this.i = i;
		}


		@Override
		public String toString() {
			return String.format("[%d,%s]", i, str);
		}
		
	}
}
